package com.zlsy.springbootdemo.gc;

import java.lang.ref.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhouliang
 * @date 2021/1/30 11:50
 */
public class ReferenceType {
  private static ReferenceQueue<User> rq = new ReferenceQueue<User>();

  private static void printQueue(String sr) {
    Reference<? extends User> poll = rq.poll();
    if (Objects.nonNull(poll)) {
      System.err.println("the gc object reference == " + sr + " = " + poll.get());
    }
  }

  private static void testSoftReference() {
    List<SoftReference<User>> list = new ArrayList<SoftReference<User>>();
    for (int i = 0; i < 10; i++) {
      SoftReference<User> sr = new SoftReference<User>(new User("soft " + i), rq);

      System.err.println("now the soft user == " + sr.get());

      list.add(sr);
    }

    System.gc();

    try {
      Thread.sleep(1000L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    printQueue("soft");
  }

  private static void testWeakReference() {
    List<WeakReference<User>> list = new ArrayList<WeakReference<User>>();
    for (int i = 0; i < 10; i++) {
      WeakReference<User> sr = new WeakReference<User>(new User("soft " + i), rq);

      System.err.println("now the soft user == " + sr.get());

      list.add(sr);
    }

    System.gc();

    try {
      Thread.sleep(1000L);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    printQueue("weak");
  }

    private static void testPhantomReference() {
        List<PhantomReference<User>> list = new ArrayList<PhantomReference<User>>();
        for (int i = 0; i < 10; i++) {
            PhantomReference<User> sr = new PhantomReference<User>(new User("soft " + i), rq);

            System.err.println("now the soft user == " + sr.get());

            list.add(sr);
        }

        System.gc();

        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        printQueue("phantom");
    }

  public static void main(String[] args) {
    testSoftReference();
      testWeakReference();
      testPhantomReference();
  }
}
